package cn.zyy.hotel.service.impl;

import cn.zyy.hotel.dao.UserMapper;
import cn.zyy.hotel.entity.User;
import cn.zyy.hotel.service.UserService;
import cn.zyy.hotel.utils.PasswordUtil;
import cn.zyy.hotel.utils.SystemConstant;
import cn.zyy.hotel.utils.UUIDUtils;
import cn.zyy.hotel.vo.UserVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    //添加用户
    public int addUser(User user) {
        //自动生成盐值
        user.setSalt(UUIDUtils.randomUUID());
        //密码加密
        user.setPassword(PasswordUtil.md5(user.getPassword(),user.getSalt(), SystemConstant.PASSWORD_COUNT));
        return userMapper.addUser(user);
    }

    //根据用户名查询用户信息
    public User selectUserByName(String loginName) {
        return userMapper.selectUserByName(loginName);
    }

    //用户登录
    public User login(String loginName, String password) {
        //调用查询用户信息的方法
        User loginUser = userMapper.selectUserByName(loginName);
        //判断对象是否为空
        if (loginUser != null){
            //密码加密
            String newPassword = PasswordUtil.md5(password,loginUser.getSalt(), SystemConstant.PASSWORD_COUNT);
            //比较密码是否相等
            if (loginUser.getPassword().equals(newPassword)){
                return loginUser;
            }
        }
        return null;
    }

    //根据手机号查询用户信息
    public User selectUserByPhone(String phone) {
        return userMapper.selectUserByPhone(phone);
    }

    //根据身份证号查询用户信息
    @Override
    public User selectUserByIdCard(String idCard) {
        return userMapper.selectUserByIdCard(idCard);
    }

    //根据邮箱查询用户信息
    @Override
    public User selectUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    //修改用户信息
    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    //修改用户密码
    @Override
    public int updatePwd(UserVO userVO) {
        //必须先设置盐值，再给密码重新加密赋值
        userVO.setSalt(UUIDUtils.randomUUID());
        userVO.setPassword(PasswordUtil.md5(userVO.getNewPassword(),userVO.getSalt(), SystemConstant.PASSWORD_COUNT));
        return userMapper.updatePwd(userVO);
    }




}
